package com.appfront;

import java.io.File;
import java.util.ArrayList;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.Toast;
import android.view.KeyEvent;
import android.widget.TextView;

import com.auxtools.FileChooserAdapter;
import com.auxtools.FileChooserAdapter.FileInfo;
import com.appfront.debug.App;

public class FileChooserActivity extends Activity {
	
	private GridView mGridView;
	private View mBackView;
	private View mBtExit;
	private TextView mTvPath ;
	private EditText inpultUserID;
	private Button selectUserID;
	
	private String mSdcardRootPath ;  //sdcard 根路径
	private String mLastFilePath ;    //当前显示的路径
	
	private ArrayList<FileInfo> mFileLists  ;
	private FileChooserAdapter mAdatper ;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.filechooser_show);

		//mSdcardRootPath = Environment.getExternalStorageDirectory().getAbsolutePath();// �õ�sdcardĿ¼
		mSdcardRootPath = App.GetSDCardPath();

		//mBackView = findViewById(R.id.imgBackFolder);
		//mBackView.setOnClickListener(mClickListener);
		inpultUserID = (EditText) findViewById(R.id.inputFolder);
		selectUserID = (Button) findViewById(R.id.selectFolder);
		mBtExit = findViewById(R.id.btExit);
		mBtExit.setOnClickListener(mClickListener);
		
		mTvPath = (TextView)findViewById(R.id.tvPath);
		
		mGridView = (GridView)findViewById(R.id.gvFileChooser);
		mGridView.setEmptyView(findViewById(R.id.tvEmptyHint));
		mGridView.setOnItemClickListener(mItemClickListener);
		setGridViewAdapter(mSdcardRootPath, inpultUserID.getText().toString());

		selectUserID.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				updateFileItems(mLastFilePath, inpultUserID.getText().toString());
			}
		});
	}
	//配置适配器
	private void setGridViewAdapter(String filePath, String userID) {
		updateFileItems(filePath, userID);
		mAdatper = new FileChooserAdapter(this , mFileLists);
		mGridView.setAdapter(mAdatper);
	}
	//根据路径更新数据，并且通知Adatper数据改变
	private void updateFileItems(String filePath, String userID) {
		mLastFilePath = filePath ;
	//	mTvPath.setText(mLastFilePath);
		mTvPath.setText("弹力带康复机-测试报告查询");
		
		if(mFileLists == null)
			mFileLists = new ArrayList<FileInfo>() ;
		if(!mFileLists.isEmpty())
			mFileLists.clear() ;
		
		File[] files = folderScan(filePath);
		if(files == null) 
			return ;
		
		for (int i = 0; i < files.length; i++) {
			if(files[i].isHidden())  // 不显示隐藏文件
				continue ;
			
			String fileAbsolutePath = files[i].getAbsolutePath() ;
			String fileName = files[i].getName();
		    boolean isDirectory = false ;
			if (files[i].isDirectory()){
				isDirectory = true ;
				if(!userID.equals("log"))
					continue;				//不显示 文件夹
			}
			if(!fileName.startsWith(userID))
				continue;
			FileInfo fileInfo = new FileInfo(fileAbsolutePath , fileName , isDirectory) ;
			mFileLists.add(fileInfo);
		}
		//When first enter , the object of mAdatper don't initialized
		if(mAdatper != null)
		    mAdatper.notifyDataSetChanged();  //重新刷新
	}
	//获得当前路径的所有文件
	private File[] folderScan(String path) {
		File file = new File(path);
		File[] files = file.listFiles();
		return files;
	}
	
	private View.OnClickListener mClickListener = new  OnClickListener() {
		public void onClick(View v) {
			switch (v.getId()) {
			//case R.id.imgBackFolder:
			//	backProcess();
			//	break;
			case R.id.btExit :
				setResult(RESULT_CANCELED);
				finish();
			    break ;
			default :
			    	break ;
			}
		}
	};
	
	private AdapterView.OnItemClickListener mItemClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> adapterView, View view, int position,
				long id) {
			FileInfo fileInfo = (FileInfo)(((FileChooserAdapter)adapterView.getAdapter()).getItem(position));
			if(fileInfo.isDirectory())   //点击项为文件夹, 显示该文件夹下所有文件
				updateFileItems(fileInfo.getFilePath(), "log") ;
			else if(fileInfo.isPdfFile()){  //是pDF文件 ， 则将该路径通知给调用者
				//officeFile：本地文档；type：文档MIMEType类型，可以使用文件格式后缀
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				//officeFile：本地文档；type：文档MIMEType类型，可以使用文件格式后缀
				intent.setDataAndType(Uri.fromFile(new File(fileInfo.getFilePath())), "application/pdf");
				FileChooserActivity.this.startActivity(intent);
//			    Intent intent = new Intent();
//			    intent.putExtra(LoginActivity.EXTRA_FILE_CHOOSER , fileInfo.getFilePath());
//			    setResult(RESULT_OK , intent);
			    finish();
			}
			else {   //其他文件.....
				toast(getText(R.string.open_file_error_format));
			}
		}
	};
    
	public boolean onKeyDown(int keyCode , KeyEvent event){
		if(event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode()
			== KeyEvent.KEYCODE_BACK){
			backProcess();   
			return true ;
		}
		return super.onKeyDown(keyCode, event);
	}
	//返回上一层目录的操作
	public void backProcess(){
		//判断当前路径是不是sdcard路径 ， 如果不是，则返回到上一层。
		if (!mLastFilePath.equals(mSdcardRootPath)) {  
			File thisFile = new File(mLastFilePath);
			String parentFilePath = thisFile.getParent();
			updateFileItems(parentFilePath, "log");
		} 
		else {   //是sdcard路径 ，直接结束
			setResult(RESULT_CANCELED);
			finish();
		}
	}
	private void toast(CharSequence hint){
	    Toast.makeText(this, hint , Toast.LENGTH_SHORT).show();
	}
}